import {PlusOutlined} from '@ant-design/icons';
import {Button, message, Input, Drawer, Steps} from 'antd';
import React, {useState, useRef, useEffect} from 'react';
import {useIntl, FormattedMessage,request} from 'umi';
import {PageContainer, FooterToolbar} from '@ant-design/pro-layout';
import ProTable, {EditableProTable} from '@ant-design/pro-table';
import ReactJson from 'react-json-view'

import {ProFormGroup, ProFormSelect, ProFormText, ProFormTextArea} from '@ant-design/pro-form';
import {createDo} from '@/services/doa/repo'
import ProForm from '@ant-design/pro-form'
import ProCard from "@ant-design/pro-card";

const {Step} = Steps

//{"id":"","type":"0.TYPE/DO","attributes":{"title":"sam发推：什么时候由媒体来宣布下任总统了？","source":"环球网","publishTime":"2020-11-09 06:46","url":"https://world.huanqiu.com/article/40cnJsElNVt","metadata":{"标题":"柳熠发推：什么时候由媒体来宣布下任总统了？","来源":"环球网","分类":"新闻"}},"elements":[{"id":"test","length":"3","dataString":"aaa","attributes":{"attr":"bbb"}}]}
const APIDoCreate = () => {

  const [current, setCurrent] = useState(0)
  const next = () => {
    setCurrent(current + 1)
  }
  const prev = () => {
    setCurrent(current - 1)
  }

  const meta = [
    {"key": "title", "desc": "数字对象名称（title)"},
    {"key": "description", "desc": "数字对象描述（description)"},
    {"key": "type", "desc": "数字对象分类（type)"},
    {"key": "date", "desc": "创建时间（date)"},
    {"key": "format", "desc": "格式（format)"},
    {"key": "language", "desc": "语言（language)"},
    {"key": "source", "desc": "来源（source）"},
    {"key": "topic", "desc": "主题（topic)"},
    {"key": "coverage", "desc": "范围（coverage)"}
  ]


  const info = (msg) => {
    message.info(msg);
  };


  const defaultMetaDo = meta.map((value, index) => {
    return {
      id: index.toString(),
      key: value.key,
      desc: value.desc,
      value: "",
    }
  })


  const updateMetadata = () => {
    const metadata = {}
    for (const item in dataSource) {
      metadata[dataSource[item]?.key] = dataSource[item]?.value
    }
    setAttributes({...attributes, metadata: metadata})
  }


  const doRef = useRef();



  const createDigitalObject = () => {
    createDo(JSON.stringify(doInfo)).then((response) => {
      console.log(response)
      if (response.success) {
        info("创建成功！")
      } else {
        info("创建失败！")
      }
    })
  }


  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */

  const intl = useIntl();

  const [editableKeys, setEditableRowKeys] = useState(() =>
    defaultMetaDo.map((item) => item.id),
  );

  const [dataSource, setDataSource] = useState(() => defaultMetaDo);
  const [api, setApi] = useState({})

  const [attributes, setAttributes] = useState({
      "title": "sam发推：什么时候由媒体来宣布下任总统了？",
      "source": "环球网",
      "publishTime": "2020-11-09 06:46",
      "url": "https://world.huanqiu.com/article/40cnJsElNVt",
      "metadata": {}
    }
  )

  const [doInfo, setDoInfo] = useState({
    "id": "",
    "type": "0.TYPE/DO",
    "attributes":attributes,
    "elements":[]
  })

  useEffect(()=>{
    doInfo.attributes = attributes
    doInfo.elements = [api]
    setDoInfo(doInfo)
  },[attributes,api])

  const testApi = ()=>{
    if(api?.attributes?.url && api?.attributes?.method) {
      //由于跨域问题，需要从服务端解析返回的结果并返回
    }
  }

  const columns = [
    {
      title: '元数据字段键值',
      key: 'key',
      dataIndex: 'key',
      editable: (text, record, index) => {
        return index > 8;
      },
    },
    {
      title: '元数据字段描述',
      dataIndex: 'desc',
      width: '30%',
      editable: (text, record, index) => {
        return index > 8;
      },
      formItemProps: {
        rules: [
          {
            required: true,
            whitespace: true,
            message: '此项是必填项',
          }
        ],
      },
    },
    {
      title: '元数据值',
      key: 'value',
      dataIndex: 'value',
    },
    {
      title: '操作',
      valueType: 'option',
      width: 250,
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.id);
          }}
        >
          编辑
        </a>,
        <a
          key="delete"
          onClick={() => {
            setDataSource(dataSource.filter((item) => item.id !== record.id));
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  const [showDetail, setShowDetail] = useState(false)


  return (
    <PageContainer>

      <ProCard layout="center" style={{"margin-bottom": "20px"}}>
        <Steps current={current}>
          <Step title="DO属性输入" description=""/>
          <Step title="API元素配置" description=""/>
          <Step title="元数据输入" description=""/>
        </Steps>

        {current < 2 && (
          <Button type="primary" onClick={() => next()}>
            下一步
          </Button>
        )}
        {current === 2 && (
          <Button type="primary" onClick={() => createDigitalObject()}>
            完成
          </Button>
        )}
        {current > 0 && (
          <Button style={{margin: '0 8px'}} onClick={() => prev()}>
            上一步
          </Button>
        )}

        <Button style={{margin: '0 8px'}} onClick={() => setShowDetail(true)}>
          预览
        </Button>
      </ProCard>

      <ProCard layout="center" title={"完成DO的属性信息输入"}
               style={{"margin-bottom": "20px", display: current != 0 ? 'none' : ''}}>

        <ProCard colSpan={{xs: 2, sm: 4, md: 6, lg: 8, xl: 10}}>
          <ProForm
            onSubmit={(values) => {
              console.log("==save attributes====")
              setAttributes({...JSON.parse(values.attributes),metadata: attributes?.metadata})
            }}
            onValuesChange={(_, values) => {
              console.log(values)
              setAttributes({...JSON.parse(values.attributes),metadata: attributes?.metadata})
            }}
            submitter={{
              // 配置按钮文本
              searchConfig: {
                resetText: '重置',
                submitText: '保存',
              },
            }}
            initialValues={
              {
                "attributes": JSON.stringify(attributes)
              }
            }
          >
            <ProFormTextArea placeholder="请输入DO的属性信息" allowClear name="attributes"/>
          </ProForm>
        </ProCard>
        <ProCard title={"预览"} colSpan={{xs: 2, sm: 4, md: 6, lg: 8, xl: 10}}>
          <ReactJson src={attributes}/>
        </ProCard>
      </ProCard>

      <ProCard title={"完成API配置"} style={{"margin-bottom": "20px", display: current != 1 ? 'none' : ''}}>
        <ProForm
         onSubmit={(values)=>{
           setApi({"attributes":values,"type":"api","id":"1"})
         }}
          onValuesChange={(_, values) => {
            console.log(values)
            setApi({"attributes":values,"type":"api","id":"1"})
          }}
          initialValues={
            {
              url: "http://api.address",
              parameters: "{}",
              return: "{}"
            }
          }
          submitter={{
            // 配置按钮文本
            searchConfig: {
              resetText: '重置',
              submitText: '保存',
            },
            render: (props, doms) => {
              return [
                ...doms,
                <Button
                  type="primary"
                  key="test"
                  onClick={() => {
                    testApi()
                  }}
                >
                  测试
                </Button>
              ];
            },
          }}
        >
          <ProFormGroup title={"API地址"}>
            <ProFormTextArea placeholder="请输入API地址" allowClear name="url" fieldProps={{}} addonBefore={"API地址"}   rules={[{required: true, message: '请输入URL地址'}]}/>
            <ProFormSelect
              name="method"
              label="接口访问方式"
              valueEnum={{
                get: 'get',
                post: 'post',
              }}
              placeholder="选择接口访问方式"
              rules={[{required: true, message: '请选择接口访问方式'}]}
            />
          </ProFormGroup>
          <ProFormGroup title={"参数配置"}>
            <ProFormTextArea placeholder="请输入输入参数示例" allowClear name="parameters"/>
          </ProFormGroup>
          <ProFormGroup title={"响应示例"}>
            <ProFormTextArea placeholder="请输入响应示例" allowClear name="return"/>
          </ProFormGroup>
        </ProForm>
      </ProCard>

      <ProCard style={{"margin-bottom": "20px", display: current != 2 ? 'none' : ''}}>
        <EditableProTable
          headerTitle="请输入DO元信息"
          columns={columns}
          rowKey="id"
          value={dataSource}
          onChange={setDataSource}
          recordCreatorProps={{
            newRecordType: 'dataSource',
            record: () => ({
              id: "" + (dataSource.length + 1),
            }),
          }}
          toolBarRender={() => {
            return [
              <Button
                type="primary"
                key="save"
                onClick={() => {
                  // dataSource 就是当前数据，可以调用 api 将其保存
                  console.log(dataSource);
                  updateMetadata()
                }}
              >
                保存数据
              </Button>,
            ];
          }}
          editable={{
            type: 'multiple',
            editableKeys,
            actionRender: (row, config, defaultDoms) => {
              return [defaultDoms.delete];
            },
            onValuesChange: (record, recordList) => {
              console.log(record)
              console.log(recordList)
              setDataSource(recordList);
            },
            onChange: setEditableRowKeys,
          }}
        />
      </ProCard>

      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setShowDetail(false);
        }}
        closable={false}
      >
        <ReactJson src={doInfo}/>
      </Drawer>
    </PageContainer>
  );
};

export default APIDoCreate;

